#!/bin/bash

top=""
server_name=""
listen=""
root=""
placeholder=""
save_path=""
# 支持https
enable_https=0
# 解析php
enable_php=0
# 创建代理
enable_proxy=0

format(){
    printf "  %-30s%-10s" "$1" "$2"
    echo 
}

usage(){
    echo "Usage:"
    format "-h,--help" "Get help docuement"
    format "-p,--port" "Listen port，default 80 or 443"
    format "-r,--root" "Root directory"
    format "-n,--name" "server 名称"
    format "-o,--output" "输出位置"
    format "--https" "支持https"
    format "--top" "设置顶级域名,com、cn等"
    format "--php" "解析php"
    format "--proxy" "设置代理，如代理nodejs、go等"
    echo "Description:"
    echo "  未指定server name的时候，将使用root中的最后一级目录+top拼接域名"
    echo "  set: -root /www/demo --top com"
    echo "  get: server_name: demo.com"
}

eval set -- $(getopt -q -o "hp:r:n:o:" -l help,top:,port:,root:,name:,output:,https,php,proxy -- "$@")

while [ -n $1 ]
do
    case $1 in
        -h|--help) 
            usage
            exit
        ;;
        -p|--port)
            listen="$2"
            shift 2
        ;;
        -r|--root)
            root="$2"
            shift 2
        ;;
        -n|--name)
            server_name="$2"
            shift 2
        ;;
        -o|--output)
            save_path="$2"
            shift 2
        ;;
        --top)
            top="$2"
            shift 2
        ;;
        --https)
            enable_https=1
            shift 1
        ;;
        --php)
            enable_php=1
            shift 1
        ;;
        --proxy)
            enable_proxy=1
            shift 1
        ;;
        *)
            break
        ;;
    esac
done

if [[ ${#save_path} -eq 0 || ! -d $save_path ]]
then
    if [ -d "/usr/local/docker/conf/nginx/1.22.1/conf.d" ]
    then
        save_path="/usr/local/docker/conf/nginx/1.22.1/conf.d"
    else
        echo "Error:Please use -o or --output to specify the output location"
        exit 1
    fi
fi

#
# 顶级域名设置
#
setDomainSuffix(){
    placeholder=""
    while true
    do
        
        if [ ${#placeholder} -eq 0 ]
        then
            placeholder="请输入顶级域名[默认com]: "
        fi
        
        read -p $placeholder parameter
        
        if [ ${#parameter} -eq 0 ]
        then
            top="com"
            break
        else
            check_res=`echo $parameter | sed "s/[a-z]//g"`
            if [ ${#check_res} -ne 0 ]
            then
                placeholder="顶级域名只能是字母,请重新输入[默认com]:"
            else
                top=$parameter
                break;
            fi
        fi
    done
}

#
# 监听端口设置
#
setListenPort(){
    placeholder=""
    while true
    do
        if [ ${#placeholder} -eq 0 ]
        then
            placeholder="请输入端口[默认80]: "
        fi
        
        read -p $placeholder parameter
        if [ ${#parameter} -ne 0 ]
        then
            check_res=`echo $parameter | sed "s/[0-9]//g"`
            if [ ${#check_res} -ne 0 ]
            then
                placeholder="端口只能是整数型，请重新输入[默认80]: "
                continue
            fi
            listen=$parameter
        else
            if [ $enable_https -eq 1 ]
            then
                listen="443"
            else
                listen="80"
            fi
        fi
        break
    done
}

#
# 项目路root设置
#
setProjectRoot(){
    placeholder=""
    while true
    do
        if [ ${#placeholder} -eq 0 ]
        then
            placeholder="请输入项目root: "
        fi
        read -e -p ${placeholder}  parameter
        if [[ ${#parameter} -eq 0 || ! -d $parameter ]]
        then
            placeholder="root不是一个路径,请重新输入root: "
            continue
        fi
        root=$parameter
        break
    done
}

#
# 从root中提取最后一级目录作为server name
#
parseRootToServerName(){
    paths=(`echo ${root} | sed "s/\// /g"`)
    # 变成数组取出最后一个
    server_name=${paths[-1]}
}

#
# server name设置
# 可以输入一个路径或者一个字符串
#
setServerName(){
    placeholder=""
    while true
    do
        if [ ${#placeholder} -eq 0 ]
        then
            placeholder="请输入server_name:"
        fi
        
        read -e -p "$placeholder" parameter
        
        # 没有输入参数的时候，从roo中获取
        if [ ${#parameter} -eq 0 ]
        then
            parseRootToServerName
        else
            # server_name中只能包含数字、字母、.
            check_res=`echo $parameter | sed "s/[a-z0-9.]//g"`
            
            if [ ${#check_res} -ne 0 ]
            then
                placeholder="server_name错误，请重新输入: "
                continue
            else
                server_name=$parameter
            fi
        fi
        break
    done
}

#
# 写入http server 配置
#
writeHttpServer(){

    if [ "${#1}" -eq 0 ]
    then
        return 1
    fi
    
    location=""
    route_php=""
    if [ $enable_php -eq 1 ]
    then
       location="location / {
        index index.php index.html index.htm;
        try_files \$uri \$uri/ /index.php?\$query_string;
        # thinkphp map
        #if (!-e \$request_filename) {
        #    rewrite  ^(.*)$  /index.php?s=/\$1  last;
        #    break;
        #}
    }"
        route_php="location ~ \.php$ {
        fastcgi_index index.php;
        fastcgi_pass php:9000;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }"
    else
        location="location / {
        index index.html index.htm;   
    }"
    fi

    if [ $enable_https -eq 1 ]
    then
        ssl="
    ssl_certificate /etc/letsencrypt/live/$server_name/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$server_name/privkey.pem;
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;"
        listen="$listen ssl"
    else
        ssl=""
    fi

    content="server {
    listen $listen;
    server_name $server_name;
    root $root;
    #access_log  /var/log/nginx/$server_name.access.log  main;
    #error_page  404              /404.html;
    #error_page 500 502 503 504 /50x.html;
    $location
    $route_php
    $ssl
}"

    sudo echo "$content" > "$1" 2>/dev/null

    if [ $? -eq 0 ]
    then
        return 0
    fi
    
    return 1
}

if [ ${#root} -eq 0 ]
then
    setProjectRoot
    setDomainSuffix
    setListenPort
else
    if [ ${#server_name} -eq 0 ]
    then
        parseRootToServerName
    fi
    
    if [ ${#top} -eq 0 ]
    then
        top="com"
    fi
    
    if [ ${#listen} -eq 0 ]
    then
        if [ $enable_https -eq 1 ]
        then
            listen="443"
        else
            listen="80"
        fi
    fi
fi

if [ ${#server_name} -eq 0 ]
then
    setServerName
fi

# 判断server_name是否以顶级域名结尾
`echo $server_name | grep -q -E "\.$top$"`
if [ $? -ne 0 ]
then
    server_name="$server_name.$top"
fi

save_path=$(echo $save_path | sed "s/\/\+$//")

 # 协议
protocol="http"
if [ $enable_https -eq 1 ]
then
    protocol="https"
fi

filename="$protocol.$server_name.$listen.conf"
http_config_path="$save_path/$filename"

if [ ! -f $http_config_path ]
then
    `sudo touch $http_config_path `
    `sudo chmod 777 $http_config_path `
    if [ $? -eq 0 ]
    then
        writeHttpServer $http_config_path
    fi
    cat $http_config_path
else
    echo "Error:"
    echo "file exist, please execute : sudo rm -rf $http_config_path"
fi
